﻿@inject IPeopleService peopleService
@inject IUserStatusService statusService
@inject ContextMenuService contextMenuService
@inject NavigationManager NavigationManager
@inject ILogger<AIObject> logger
@inject IDialogService DialogService


<div class="object" title="@ObjectName" style="@ObjectStylePos" id="@theObject.PersonId">
    @if ( Editing )
    {
        <div class="object-editor">
            <MudAutocomplete T="string" Placeholder="Add Name" SearchFunc="SearchNames"
                             @bind-Value="@TypeAheadName" ShowProgressIndicator="true" MinCharacters="2"
                             CoerceValue="true" DebounceInterval="250" Clearable="true" Immediate="false"
                             Adornment="Adornment.Start" AdornmentIcon="@Icons.Material.Filled.Sell"
                             Variant="UIConstants.MudVariant" @onblur="LostFocus"
                             class="tag-autocomplete" PopoverClass="tag-autocomplete-popover"/>
        </div>
    }
    else
    {
        <div class="object-text" @onclick="EditName" title="Click to Edit">@ObjectName</div>
    }
</div>

@code {

    [Parameter] public ImageObject theObject { get; set; }

    [Parameter] public Action<ImageObject> OnObjectChanged { get; set; }

    private bool Editing { get; set; }

    private string nameText = string.Empty;

    private string TypeAheadName
    {
        get => nameText;
        set => nameText = value;
    }

    public string ObjectName => theObject.ToString();
    public string ObjectTitle => $"{ObjectName} - click to edit";

    private string ObjectStylePos
    {
        get
        {
            var imgWidth = theObject.Image.MetaData.Width > 0 ? theObject.Image.MetaData.Width : 800;
            var imgHeight = theObject.Image.MetaData.Height > 0 ? theObject.Image.MetaData.Height : 800;

            var xPercent = theObject.RectX * 100 / imgWidth;
            var yPercent = theObject.RectY * 100 / imgHeight;
            var wPercent = theObject.RectWidth * 100 / imgWidth;
            var hPercent = theObject.RectHeight * 100 / imgHeight;
            var pos = $"top:{yPercent}%;left:{xPercent}%;width:{wPercent}%;height:{hPercent}%;";

            return pos;
        }
    }

    private void ShowContextMenu(MouseEventArgs args)
    {
        if ( theObject.Type != ImageObject.ObjectTypes.Face.ToString() )
            return;

        var menuList = new List<ContextMenuItem>
        {
            new() { Text = $"Find more photos containing this person", Value = 0 }
        };

        contextMenuService.Open(args, menuList, args =>
        {
            contextMenuService.Close();
            switch ( args.Value )
            {
                case 0:
                    NavigationManager.NavigateTo($"/?personid={theObject.PersonId}");
                    break;
            }
        });
    }

    private void LostFocus()
    {
        Editing = false;
        StateHasChanged();
    }

    private async Task EditName()
    {
        if ( !Editing && theObject.Type == ImageObject.ObjectTypes.Face.ToString() )
        {
            Editing = true;

            var options = new MudBlazor.DialogOptions { MaxWidth = MaxWidth.Small, CloseButton = false, CloseOnEscapeKey = true };
            var parameters = new DialogParameters { { "theObject", theObject } };
            var dialog = DialogService.Show<NameDialog>("Add Name", parameters);
            var result = await dialog.Result;

            if ( !dialog.Result.IsCanceled )
            {
                // Reset the tag
                Editing = false;

                OnObjectChanged?.Invoke(theObject);

                StateHasChanged();
            }
        }
    }

    private async Task<IEnumerable<string>> SearchNames(string text, CancellationToken token)
    {
        var list = await peopleService.GetPeopleNames(text.Trim());
        return list;
    }

}